package com.fsoft.core.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;

/**
 * F-Soft IP工具类，主要功能：通过HttpServletRequest 获取客户端的IP地址
 * @package com.fsoft.core.utils
 * @author Fish
 * @email it.fish2010@foxmail.com
 * @date 2019-11-25
 * @CopyRight © F-Soft
 **/
public class WebUtils {
	private static Logger logger = LoggerFactory.getLogger(WebUtils.class);

	/**
	 * 通过http Header 获取IP地址 <BR>
	 * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址 <BR>
	 * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址;X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
	 */
	public static final String getIpAddr(HttpServletRequest request) {
		String ip = null;
		try {
			ip = request.getHeader("x-forwarded-for");
			if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("fsoft-web-clientIp"); // 优先通过项目自身的JS插件获取客户端IP
			}
			if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		} catch (Exception e) {
			logger.error("IPUtils ERROR ", e);
		}
		return ip;
	}

	/**
	 * 向指定 URL 发送Get方法的请求
	 * 
	 * @param url 发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应内容
	 * @throws IOException
	 */
	public static String httpGet(String url, Map<String, String> param, Map<String, String> headers) throws IOException {
		BufferedReader in = null;
		OutputStream out = null;
		String result = "";
		HttpURLConnection connection = null;
		try {
			if (param != null) {
				url = url + "?";
				StringBuilder stringBuilder = new StringBuilder();
				for (String key : param.keySet()) {
					stringBuilder.append("&" + key + "=" + param.get(key));
				}
				url = url + stringBuilder.toString();
			}
			URL realUrl = new URL(url);
			connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			if (headers != null) {
				for (String key : headers.keySet()) {
					connection.setRequestProperty(key, headers.get(key));
				}
			}
			InputStream inputStream = connection.getInputStream();
			int len = inputStream.available();
			byte[] byteResult = new byte[len];
			inputStream.read(byteResult);
			result = new String(byteResult);
		} finally {
			connection = null;
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 判断是否为IE浏览器
	 * @param request
	 * @return
	 */
	public static Boolean isIEBrowser(HttpServletRequest request) {
		String[] ieBrowserSignals = { "MSIE", "Trident", "Edge" };
		String userAgent = request.getHeader("User-Agent");
		for (String signal : ieBrowserSignals) {
			if (userAgent.contains(signal)) {
				return true;
			}
		}
		return false;
	}
}
